<template>
  <div>
    <SelectTaskDialog ref="selectTaskDialog" :knowledgeLibId="crtRow.category"
                                @callBack="selectSimilarTaskItem"/>
    <SimilarTaskItemTableDialog ref="similarTaskItemTableDialog"
                                :containsSimilarTaskItemList="containsSimilarTaskItemList"
                                :knowledgeLibId='crtRow.category'
                                @quit="quit" @update="update" @create="create"/>
    <el-drawer
      :title="knowledgeUnitName"
      size="50%"
      :modal="false"
      :visible.sync="drawerVisible"
      @close="contentEditFlag = false; drawerVisible = false">
      <el-button v-if="!isShow" size="small" @click="editContent" v-html="contentEditFlag ? '保存' : '编辑'"></el-button>
      <div v-show="contentEditFlag" style="margin-top: 10px">
        <div style="width: 100px; display: inline-block; text-align: right; vertical-align: middle; ">知识单元名称:</div>
        <KindEditor :content.sync="knowledgeUnitName"
                    editor-type="Input" style="width: 300px; display: inline-block; vertical-align: middle; "/>
      </div>
      <div ref="contentDiv" :contenteditable="contentEditFlag"
           :style="{backgroundColor : contentEditFlag ? 'aliceblue' : 'antiquewhite'}"
           v-html="knowledgeUnitContent"></div>
    </el-drawer>

    <el-row>
      <el-col :span="12">
        <el-button icon="el-icon-plus" size="small" type="primary" @click="batchSelectTask">批量创建子任务</el-button>
        <el-button size="small" @click="$router.push('/material/taskHistory')">创建子任务历史</el-button>
      </el-col>
      <el-col :span="12">
        <Search @confirm="searchConfirm" ref="Search"></Search>
      </el-col>
    </el-row>
    <el-row>
      <el-table ref="knowledgeUnitTable"
                :data='knowledgeUnitList'
                :height="tableHeight"
                show-checkbox
                stripe
                use-virtual>
        <el-table-column align="center"
                         :selectable="item => UTIL.isNotEmpty(item.category) && UTIL.isEmpty(item.knowledgeId)"
                         type="selection"
                         width="50">
        </el-table-column>
        <el-table-column label="知识名称" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-html="scope.row.name"/>
          </template>
        </el-table-column>
        <el-table-column label="图书" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-html="scope.row.bookName"/>
          </template>
        </el-table-column>
        <el-table-column label="ISBN" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-html="scope.row.bookIsbn"/>
          </template>
        </el-table-column>
        <el-table-column label="所属目录" min-width="150" prop="bookCatalogPath" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="类别" min-width="50" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="white-space: pre-line;" v-html="scope.row.categoryVo"/>
          </template>
        </el-table-column>
        <el-table-column label="分类标签" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <span style="white-space: pre-line;" v-html="scope.row.tagVo"/>
          </template>
        </el-table-column>
        <el-table-column label="自由标签" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <span v-html="scope.row.customTagVo"/>
          </template>
        </el-table-column>
        <el-table-column label="入库时间" min-width="200" prop="submitMaterialTime" show-overflow-tooltip>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <span><el-link @click.prevent="detail(scope.row)">详情</el-link></span>
          <span><el-link :disabled="UTIL.isEmpty(scope.row.category) || UTIL.isNotEmpty(scope.row.knowledgeId)"
                         @click.prevent="selectTask(scope.row)">新建子任务</el-link></span>
            <span><el-link v-if="!isShow" type="danger"
                           @click.prevent="deleteKnowledgeUnit(scope.row)">删除</el-link></span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :page-size="searchKnowledgeUnit.pageSize"
        :page-sizes="[5, 10, 15, 20, 50, 100]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        style="text-align: right;"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"></el-pagination>
    </el-row>
  </div>
</template>

<script>
import Search from './Search'
import SelectTaskDialog from './SelectTaskDialog'
import SimilarTaskItemTableDialog from '../task/SimilarTaskItemTableDialog'
export default {
  name: "MaterialTable",
  components: {Search, SelectTaskDialog, SimilarTaskItemTableDialog},
  data() {
    return {
      containsSimilarTaskItemList: [],
      tableHeight: CONST.WORKSPACE_HEIGHT - 85,
      customTag: [],
      knowledgeUnitList: [],
      drawerVisible: false,
      knowledgeUnitName: '',
      knowledgeUnitContent: '',
      total: 0,
      crtRow: {},
      contentEditFlag: false,
      searchKnowledgeUnit: {
        currentPage: 1,
        pageSize: 10,
      },
      isShow: false,
    }
  },
  methods: {
    batchSelectTask() {
      let crtSelection = this.$refs.knowledgeUnitTable.selection
      if (crtSelection.length === 0) {
        this.$message.warning('请选择知识单元列表')
        return
      }
      if (crtSelection.map(item => item.category).distinct().length > 1) {
        this.$message.warning('选中的知识单元类别不一致, 不能同步操作')
        return
      }
      this.selectTask(crtSelection[0])
      this.$store.commit('setCreateTaskItemType', 'multi')
    },
    quit(taskItemWithSimilarList) {
      this.containsSimilarTaskItemList.remove(taskItemWithSimilarList)
    },
    create(taskItemWithSimilarList) {
      this.containsSimilarTaskItemList.remove(taskItemWithSimilarList)
    },
    update(taskItemWithSimilarList, similarTaskItem) {
      this.crtRow.knowledgeId = similarTaskItem.knowledgeId
      this.create(taskItemWithSimilarList)
    },
    selectTask(tableRow) {
      this.$store.commit('setCreateTaskItemType', 'single')
      this.crtRow = tableRow
      this.$refs.selectTaskDialog.visible = true
    },
    selectSimilarTaskItem() {
      // 先根据知识单元名称, 查询名称类似子任务;
      let param = new URLSearchParams();
      if (this.$store.state.createTaskItemType === 'single') {
        param.append("taskItemList", JSON.stringify([{name: this.crtRow.name}]))
      }
      else {
        let nameList = this.$refs.knowledgeUnitTable.selection.map(function (item) { return {name: item.name}})
        param.append('taskItemList', JSON.stringify(nameList))
      }
      param.append("knowledgeLibId", this.crtRow.category)
      this.axios.post('/pmph/action/task/selectSimilarTaskItemList', param)
        .then((response) => {
          this.containsSimilarTaskItemList = []
          for (let taskItem of response.data) {
            if (taskItem.similarTaskItemList.length > 0) {
              this.containsSimilarTaskItemList.push(taskItem)
              this.$refs.similarTaskItemTableDialog.visible = true
            }
          }
        })
    },
    editContent() {
      if (this.contentEditFlag) {
        this.crtRow.content = this.$refs.contentDiv.innerHTML
        this.crtRow.name = this.knowledgeUnitName
        this.drawerVisible = false
        this.axios.post('/pmph/action/knowledgeUnit/updateById', this.crtRow)
          .then(() => {
          })
      }
      this.contentEditFlag = !this.contentEditFlag
    },
    searchConfirm(knowledgeUnit) {
      if (knowledgeUnit.tagParam.length > 1) {
        let tempTagParam = knowledgeUnit.tagParam.concat()
        tempTagParam.shift()
        knowledgeUnit.tagVo = JSON.stringify(tempTagParam)
      }
      knowledgeUnit.currentPage = 1
      knowledgeUnit.pageSize = this.searchKnowledgeUnit.pageSize
      this.searchKnowledgeUnit = knowledgeUnit
      this.selectKnowledgeUnitList()
    },
    handleSizeChange(value) {
      this.searchKnowledgeUnit.pageSize = value
      this.selectKnowledgeUnitList()
    },
    //分页
    handleCurrentChange: function (val) {
      this.searchKnowledgeUnit.currentPage = val;
      this.selectKnowledgeUnitList();
    },
    async detail(tableRow) {
      this.crtRow = tableRow
      this.knowledgeUnitContent = tableRow.content
      this.knowledgeUnitName = tableRow.name
      this.drawerVisible = true
    },
    deleteKnowledgeUnit(tableRow) {
      this.$confirm('确认删除知识单元?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post('/pmph/action/knowledgeUnit/deleteById', {
          id: tableRow.id
        }).then(() => {
          this.knowledgeUnitList.remove(tableRow)
        })
      })
    },
    selectKnowledgeUnitList() {
      this.axios.get('/pmph/action/knowledgeUnit/selectPage', {
        params: this.searchKnowledgeUnit
      }).then(response => {
        this.knowledgeUnitList = response.data.records
        this.total = response.data.total
      })
    },
  },
  activated() {
    this.selectKnowledgeUnitList()
  },
  created() {
    this.selectKnowledgeUnitList()
    if (this.$store.state.user.userName === 'admin') {
      return
    }
    //角色Id等于管理员角色
    for (let i = 0; i < this.$store.state.user.roleIds.length; i++) {
      if (this.$store.state.user.roleIds[i] === '1455781731549327361') {
        return;
      }
    }
    UTIL.findTreeNode(this.$store.state.menuList, item => {
      if (item.id === this.$store.state.activeId) {
        if (item.detailButton) {
          this.isShow = true
        }
      }
    })
  },
  watch: {
    containsSimilarTaskItemList(val) {
      if (val.length === 0) {
        if (this.$store.state.createTaskItemType === 'single') {
          // 路由, 跳转到单条页面;
          this.axios.post('/pmph/action/knowledgeUnit/parse2Knowledge', this.crtRow)
            .then((response) => {
              this.$store.commit('setEditingKnowledge', response.data.knowledge)
              this.$store.commit('setKnowledgeList', [response.data.knowledge])
              this.$store.commit('setKnowledgeLibFieldList', response.data.knowledgeLibFieldList)
              this.$router.push('/createKnowledgeByKnowledgeUnit')
            })
        }
        else {
          // 路由, 跳转到批量页面;
          this.axios.post('/pmph/action/knowledgeUnit/parse2KnowledgeList', this.$refs.knowledgeUnitTable.selection)
            .then((response) => {
              this.$store.commit('setKnowledgeList', response.data.knowledgeList)
              this.$store.commit('setKnowledgeUnitFieldList', response.data.knowledgeUnitFieldList)
              this.$store.commit('setKnowledgeLibFieldList', response.data.knowledgeLibFieldList)
              this.$router.push('/multiCreateKnowledge')
            })
        }
      }
    }
  }
}
</script>

<style scoped>
/deep/ .el-drawer__body {
  overflow: auto;
  margin: 0px 20px;
}
</style>
